

var Engine = {
	
	default_action	: 'dashboard',
	
	get				: function( query )	{
		
		return ( typeof query == "object" )?
				
				 query : document.querySelector( query );
	},
	
	filter			: function( query )	{
		
		nodelist	= document.querySelectorAll( query );
		list		= new Array();
		
		for( key in nodelist )
			if ( typeof nodelist[ key ] == "object" ) list.push( nodelist[ key ]);
		
		return list;
	},

	element			: function( tag, attributes ) {

  		el = document.createElement( tag );
		
		if( attributes )
			for ( key in attributes ) el.setAttribute( key, attributes[ key ]);
		
		return el;
	},

	growl			: function( message ) {
		
		growl	= Engine.element( 'div', { 'class': 'Growl' });
		growl.innerHTML = message;
		parent	= Engine.get( "aside" )
		
		while ( parent.firstChild )
				parent.removeChild(parent.firstChild);
				
		parent.appendChild( growl );

	},
	
	xhr			: function( uri, params, succesListener ) {
		
		var xhr = new XMLHttpRequest();
			xhr.addEventListener( "load", succesListener, false ); //	# progress	# load	# error	# abort
		
		var data = new FormData();
		for (var key in  params )
			data.append( key, params[ key ]);
			
			xhr.open( "POST", uri );
			xhr.send( data );
	},
	
	validateXhr			: function( data, error_override ) {
		
		
		try { json = JSON.parse( data.target.responseText ); } catch( err ) {
			
			Engine.growl( "Data error (bad json)" );
			return false;
		}
		
		if ( json.error ) {
			
			if( error_override ) return json;
				Engine.growl( "Data Error: \n" + json.error );
			
		} else if ( json.redirect ) {
			
			if( json.delay ) {
			
				if( json.message ) Engine.growl( json.message );	
				setTimeout( function( red ) { window.location = red }, Number( json.delay ) * 1000, json.redirect );
			
			} else window.location = json.redirect
		
		}
		
		return json;	
	},
	
	trigger		: function( string, listen ) {
		
		trigger = this.get( string );
		trigger.addEventListener( listen, this.triggerHandler );

	},
	
	triggerHandler		: function( e ) {
		
		trigger = e.target.id.split( '.' ).pop();
		
		if ( Engine.triggerlist[ trigger ])
			 Engine.triggerlist[ trigger ]();
			
		else Engine.xhr( 'xhr.php', { task: trigger }, Engine.validateXhr );
		
	},
	
	addView				: function( json, n ) {
		
		column = Engine.get( "section > div > div:nth-child(" + ( n +1) + ")" );
		
		if( json.content )
			column.innerHTML = json.content;
			
		if( json.elements )
			Engine.appendElements( column, json.elements );
		
	},
	
	appendElements		: function( parent, elements, update ) {
	
		if( update )
			parent.innerHTML = "";
		
		if( elements ) {
		
			parent.appendChild( container = Engine.element( 'div' ))
			elements.forEach( function( element ){
					 
					 child = new Elements[ element.type ]( element.args, element.callback );
					 container.appendChild( child );
					 if( child.post_append) child.post_append();
			});
		}
	},
	
	clearSection		: function( amount, classname ) {
		
			section = Engine.get( "section > div" );
			
			while ( section.firstChild )
					section.removeChild( section.firstChild );
			
			if( amount )	
				for( n = 0; n < amount; n++ ) section.appendChild( Engine.element( "div", { columnid: n }));
						
			if( classname )
				section.parentNode.className = classname + " grid" + amount;
					
			//// TO-DO: remove pending XHR view calls if new starts
	},
	
	findColumn			: function( target ) {
	
		while( !target.getAttribute( 'columnid' ) && target.parentNode )
				target = target.parentNode;
		
		return target.getAttribute( 'columnid' );	
	}
}

Engine.triggerlist	= {

//	ACTION Json	
	json				: function( type, action, params ) {
		
		if( !params )	params = { type: type }
		else		 	params['type'] = type
						params['action'] = action

		Engine.xhr( 'xhr.php', params, Engine.triggerlist.json_response );
	},
	json_response		: function( data ) {
		
			json = Engine.validateXhr( data );
		if( json.message )

			Engine.growl( json.message );
	},



//	ACTION Login
	login				: function() {
		
		user = Engine.get( "input[type='text']" ).value;
		pass = Engine.get( "input[type='password']" ).value;
		
		Engine.xhr( 'xhr.php', { task:'login', user:user, pass:pass }, this.login_response );
		
	},
	login_response		: function( data ) {
		
			json = Engine.validateXhr( data, true );
		if( json.error )
		
			Engine.growl( "Wrong. Please retry" );
	},
	

	
//	ACTION View	
	view				: function( type, column, params ) {
		
		if( !params || !params.action ) 
			 params 		= { action: Engine.default_action }
			 params.task	= "view"
			 params.type	= type
			 params.column	= column
		
		Engine.xhr( 'xhr.php', params, Engine.triggerlist.view_response );

	},
	view_response		: function( data ) {
		
			json = Engine.validateXhr( data );
		if( json ) {
			Engine.addView( json, Number( json.column ));
		}
	},

//	ACTION Dashboard	
	dashboard			: function() {
		
		Engine.xhr( 'xhr.php', { task:'dashboard' }, this.dashboard_response );
	},
	dashboard_response	: function( data ) {

			json = Engine.validateXhr( data );
		if( json )
			json.views.forEach( Engine.triggerlist.view ); 
		
	},
	
//	ACTION Pages	
	pages			: function() {
		
		Engine.xhr( 'xhr.php', { task:'pages' }, this.pages_response );
	},
	pages_response	: function( data ) {
		
			json = Engine.validateXhr( data );
		if( json )
			Engine.growl( json.message );
		
	},
	
//	ACTION MailChimp	
	mailchimp			: function() {
		
		Engine.clearSection( 3, 'blackwhite');
		
		Engine.triggerlist.view( 'mailchimp', 0, { action: 'options' });
		Engine.triggerlist.view( 'mailchimp', 2, { action: 'dashboard' });
	}	
}




